import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:zhaoxiaowu_app/components/view.dart';
import 'package:zhaoxiaowu_app/viewmodels/love_image_viewmodel.dart';

class LoveImageView extends StatefulWidget {
  const LoveImageView({Key? key}) : super(key: key);

  @override
  LoveImageViewState createState() => LoveImageViewState();
}

class LoveImageViewState extends State<LoveImageView> {
  final _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar("恋爱记录"),
      body: GridView.count(
        crossAxisCount: 3,
        shrinkWrap: true,
        mainAxisSpacing: 10.0,
        crossAxisSpacing: 10.0,
        padding: EdgeInsets.all(10.0),
        children: _itemBuilder(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _getImage,
        child: Icon(Icons.camera_alt),
      ),
    );
  }

  List<Widget> _itemBuilder() {
    List<Widget> widgets = [];
    if (Provider.of<LoveImageViewModel>(context).imgs.length > 0) {
      for (var e in Provider.of<LoveImageViewModel>(context).imgs) {
        widgets.add(
          Stack(
            children: [
              CachedNetworkImage(
                imageUrl: e["url"],
                imageBuilder: (context, imageProvider) => Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: imageProvider,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                placeholder: (context, url) => CircularProgressIndicator(
                  strokeWidth: 2.0,
                  color: Colors.grey,
                ),
                errorWidget: (context, url, error) => Icon(Icons.error),
              ),
              GestureDetector(
                child: Align(
                  alignment: Alignment.topRight,
                  child: Icon(
                    Icons.delete_forever,
                    color: Colors.red,
                  ),
                ),
                onTap: () => _delete(e["id"]),
              ),
            ],
          ),
        );
      }
    }
    return widgets;
  }

  void _delete(int id) async {
    print(id.toString());

    context.read<LoveImageViewModel>().deleteImage(id.toString());
  }

  void _getImage() async {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: Text("拍照"),
                leading: Icon(Icons.camera_alt),
                onTap: _camera,
              ),
              Divider(height: 1),
              ListTile(
                title: Text("相册"),
                leading: Icon(Icons.photo_album),
                onTap: _photo,
              ),
              Divider(height: 1),
              ListTile(
                title: Text("取消"),
                leading: Icon(Icons.cancel),
                onTap: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      },
    );
  }

  void _camera() async {
    Navigator.of(context).pop();
    final pickedFile = await _picker.pickImage(source: ImageSource.camera);
    context.read<LoveImageViewModel>().uploadImage(pickedFile);
  }

  void _photo() async {
    Navigator.of(context).pop();
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    context.read<LoveImageViewModel>().uploadImage(pickedFile);
  }

  void loadData() async {
    context.read<LoveImageViewModel>().getLoveImages();
  }
}
